<?php
/*
 * Plugin Name: KZ Gateway
 * Description: This plugin will tie in all the performance optimizations your WordPress application offers
 * Author: KeZong
 * Version: 1.0.0
 */
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
// $discover = file_get_contents(plugin_dir_url( __FILE__ ) . 'images/discover.svg');

 
 add_filter( 'woocommerce_payment_gateways', 'kz_add_gateway_class' ); 
function kz_add_gateway_class( $gateways ) {
	$gateways[] = 'WC_Kz_Gateway'; // 在这里添加类名称
	return $gateways;
} 
 /*
 * 类本身，请注意，它挂载到plugins_loaded动作钩子内
 */ 
add_action( 'plugins_loaded', 'kz_init_gateway_class' ); 
function kz_init_gateway_class() {
	if (!class_exists('WC_Payment_Gateway')) {
        return; // 检查WooCommerce是否已经加载
    }
 	class WC_Kz_Gateway extends WC_Payment_Gateway { 
 		/**
 		* 类构造函数，在第3步中有更多关于它的信息
 		*/ 
 		public function __construct() { 
 			$this->id = 'kz'; // 支付网关插件ID
 			$this->icon = plugin_dir_url( __FILE__ ) . 'asses/images/ccs.svg'; // 将显示在结帐页面上您的网关名称附近的图标的URL   
 			$this->has_fields = true; // 如果您需要自定义信用卡形式 
 			$this->method_title = 'Kz Gateway'; 
 			$this->method_description = 'Description of Kz payment gateway'; // 将显示在选项页面上 
 			// 网关可以支持订阅，退款，保存付款方式， 
 			// 但在本教程中，我们先从简单的支付开始 
 			$this->supports = array( 'products' );
 			// 具有所有选项字段的方法 
 			$this->init_form_fields(); // 加载设置。 
 			$this->init_settings(); 
 			$this->title = $this->get_option( 'title' ); 
 			$this->description = $this->get_option( 'description' ); 
 			$this->enabled = $this->get_option( 'enabled' ); 

 			$this->kz_domain = $this->get_option( 'kz_domain' ); 
 			$this->kz_store = $this->get_option( 'kz_store' ); 
 			$this->kz_prefix = $this->get_option( 'kz_prefix' );

 			$this->kz_api_url = $this->get_option( 'kz_api_url' );

 			$this->open_welcome = $this->get_option( 'open_welcome' );

 			// 这个动作挂钩保存设置 
 			add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
 			// 我们需要自定义JavaScript以获得令牌/样式等
 			add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts' ) ); 
 			// 您也可以在此处注册一个
 			add_action( 'woocommerce_api_kz', array( $this, 'webhook' ) ); 
 		}

 		/**
 		* 插件选项，我们也在第3步中处理它
 		*/ 
 		public function init_form_fields(){ 
 			$this->form_fields = array( 
 					'enabled' => array( 
 						'title' => 'Enable/Disable', 
 						'label' => 'Enable Kz Gateway', 
 						'type' => 'checkbox', 
 						'description' => '', 
 						'default' => 'no' ), 
 					'title' => array( 
 						'title' => 'Title', 
 						'type' => 'text', 
 						'description' => 
 						'This controls the title which the user sees during checkout.', 
 						'default' => 'Credit Card', 
 						'desc_tip' => true, ), 
 					'description' => array( 
 						'title' => 'Description', 
 						'type' => 'textarea', 
 						'description' => 'This controls the description which the user sees during checkout.', 
 						'default' => 'Pay with your credit card via our super-cool payment gateway.', ), 
 					'kz_domain' => array( 
 						'title' => '3D verified domain', 
 						'type' => 'text',
 						'description' => 'testetsets', 
 						'desc_tip' => true, ), 
 					'kz_store' => array( 
 						'title' => 'Store name', 
 						'type' => 'text',), 
 					'kz_prefix' => array( 
 						'title' => 'Order ID prefix ', 
 						'type' => 'text' ),
 					'kz_api_url' => array( 
 						'title' => 'api url', 
 						'type' => 'text',
 						'description' => '同步订单到鱼后台地址', 
 						'desc_tip' => true, ),

 					'open_welcome' => array( 
 						'title' => 'Welcome Store', 
 						'label' => 'Welcome Store', 
 						'type' => 'checkbox', 
 						'description' => '开启进入支付页面后台提示', 
 						'default' => 'yes' 
 					),
 				); 
 		}

 		/**
		* 如果您需要自定义信用卡表格，则将需要它，步骤4就是关于它的
		*/ 
		public function payment_fields() { 
			// 输出表单，但你可以关闭PHP标签和直接在HTML打印 
			echo '<fieldset id="wc-' . esc_attr( $this->id ) . '-cc-form" class="wc-credit-card-form wc-payment-form row row-kz" style="background:transparent;">'; 
			// 如果希望您的自定义支付网关支持它，请添加此操作挂钩  
			do_action( 'woocommerce_credit_card_form_start', $this->id ); 
			// 我建议使用Inique ID，因为其他网关可能已经使用#ccNo, #expdate, #cvc 
			echo '
			<div class="form-row form-row-wide kz-row col-xs-12 col-sm-12">
				<label>Card Number <span class="required">*</span></label>
				<div class="p-CardNumberInput">
					<div>
						<input id="kz_ccNo" name="kz_ccNo" type="tel" autocomplete="off" class="p-Input-input"
							placeholder="1234 1234 1234 1234" maxlength="19">
						<input hidden id="valid_card_no" name="valid_card_no" value="true">
					</div>
					<div class="p-CardIcons Input kz-cardIcon">
						<div style="position: relative;">
							<div class="p-CardBrandIcons p-CardBrandIcons--loaded p-CardBrandIcons--multiple kz"
								aria-describedby="cardBrandIconsDesc">
								<p id="cardBrandIconsDesc" class="u-visually-hidden">Supported cards include visa, mastercard,
									amex,
									discover, diners, jcb</p>
								<div class="p-CardBrandIcons-item">
									<img class="p-CardBrandIcon" alt="visa"
										src="https://js.stripe.com/v3/fingerprinted/img/visa-729c05c240c4bdb47b03ac81d9945bfe.svg">
								</div>
								<div class="p-CardBrandIcons-item">
									<img class="p-CardBrandIcon" alt="mastercard"
										src="https://js.stripe.com/v3/fingerprinted/img/mastercard-4d8844094130711885b5e41b28c9848f.svg">
								</div>
								<div class="p-CardBrandIcons-item">
									<img class="p-CardBrandIcon" alt="amex"
										src="https://js.stripe.com/v3/fingerprinted/img/amex-a49b82f46c5cd6a96a6e418a6ca1717c.svg">
								</div>
								<div class="p-CardBrandIcons-item p-CardBrandIcons-more">
									<img class="p-CardBrandIcon" alt="visa"
										src="https://js.stripe.com/v3/fingerprinted/img/visa-729c05c240c4bdb47b03ac81d9945bfe.svg">
									<img class="p-CardBrandIcon" alt="mastercard"
										src="https://js.stripe.com/v3/fingerprinted/img/mastercard-4d8844094130711885b5e41b28c9848f.svg">
									<img class="p-CardBrandIcon" alt="amex"
										src="https://js.stripe.com/v3/fingerprinted/img/amex-a49b82f46c5cd6a96a6e418a6ca1717c.svg">
									<img class="p-CardBrandIcon p-CardBrandIcon--visible" alt="discover"
										src="https://js.stripe.com/v3/fingerprinted/img/discover-ac52cd46f89fa40a29a0bfb954e33173.svg">
									<img class="p-CardBrandIcon" alt="diners"
										src="https://js.stripe.com/v3/fingerprinted/img/diners-fbcbd3360f8e3f629cdaa80e93abdb8b.svg">
									<img class="p-CardBrandIcon" alt="jcb"
										src="https://js.stripe.com/v3/fingerprinted/img/jcb-271fd06e6e7a2c52692ffa91a95fb64f.svg">
		
								</div>
							</div>
							<div class="p-CardKnownIcon">
								<div class="u-visually-hidden" id="knownCardBrandDesc">
								</div>
							</div>
							<div class="p-CardErrorIcon">
								<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"
									fill="#df1b41" role="presentation">
									<path opacity=".4" fill-rule="evenodd" clip-rule="evenodd"
										d="M15.337 4A5.5 5.5 0 1023 11.663V18a2 2 0 01-2 2H3a2 2 0 01-2-2V6a2 2 0 012-2h12.337zm6.707.293c.239.202.46.424.662.663a2.01 2.01 0 00-.662-.663zM3 9a1 1 0 011-1h5a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1V9z">
									</path>
									<path opacity=".6" fill-rule="evenodd" clip-rule="evenodd"
										d="M4 15a1 1 0 100 2h1.5a1 1 0 100-2H4zm4.8 0a1 1 0 100 2h1.5a1 1 0 100-2H8.8zm3.8 1a1 1 0 011-1h1.5a1 1 0 110 2h-1.5a1 1 0 01-1-1zm5.9-1a1 1 0 100 2H20a1 1 0 100-2h-1.5z">
									</path>
									<path fill-rule="evenodd" clip-rule="evenodd"
										d="M18.5 14a5.5 5.5 0 110-11 5.5 5.5 0 010 11zm0-1.719a1.031 1.031 0 100-2.062 1.031 1.031 0 000 2.062zm0-7.906a.687.687 0 00-.688.688V8.5a.687.687 0 101.375 0V5.062a.687.687 0 00-.687-.687z">
									</path>
								</svg>
							</div>
						</div>
					</div>
				</div>
				<p id="Field-numberError" class="p-FieldError Error" role="alert">Your card number is incomplete.</p>
			</div>';

			echo'
				<div class="form-row form-row-first kz-row col-xs-12 col-sm-6">
					<label>Expiration <span class="required">*</span></label>
					<input id="kz_expdate" name="kz_expdate" type="tel" autocomplete="off" placeholder="MM / YY"
						class="p-Input-input" maxlength="7">
						<input hidden name="valid_card_expdate" value="true">
					<p id="Field-expiryError" class="p-FieldError Error" role="alert">Your card\'s expiration date is incomplete.</p>
				</div>
				<div class="form-row form-row-last kz-row col-xs-12 col-sm-6">
					<label>CVV <span class="required">*</span></label>
					<div class="p-CardCvcInput">
						<input id="kz_cvv" name="kz_cvv" type="password" autocomplete="off" placeholder="CVV"
							class="p-Input-input" maxlength="3">
							<input hidden name="valid_card_cvv" value="true">
						<div class="p-CardCvcIcons Input">
							<p id="cvcDesc" class="u-visually-hidden">3-digit code on back of card</p>
							<div class="p-CardCvcIcons-group c-InputPadding">
								<svg class="p-CardCvcIcons-svg kz-svg kz-svg-succ kz-svg-show" width="24"
									height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="#6d6e78" role="img"
									aria-labelledby="cvcDesc">
									<path opacity=".2" fill-rule="evenodd" clip-rule="evenodd"
										d="M15.337 4A5.493 5.493 0 0013 8.5c0 1.33.472 2.55 1.257 3.5H4a1 1 0 00-1 1v1a1 1 0 001 1h16a1 1 0 001-1v-.6a5.526 5.526 0 002-1.737V18a2 2 0 01-2 2H3a2 2 0 01-2-2V6a2 2 0 012-2h12.337zm6.707.293c.239.202.46.424.662.663a2.01 2.01 0 00-.662-.663z">
									</path>
									<path opacity=".4" fill-rule="evenodd" clip-rule="evenodd"
										d="M13.6 6a5.477 5.477 0 00-.578 3H1V6h12.6z"></path>
									<path fill-rule="evenodd" clip-rule="evenodd"
										d="M18.5 14a5.5 5.5 0 110-11 5.5 5.5 0 010 11zm-2.184-7.779h-.621l-1.516.77v.786l1.202-.628v3.63h.943V6.22h-.008zm1.807.629c.448 0 .762.251.762.613 0 .393-.37.668-.904.668h-.235v.668h.283c.565 0 .95.282.95.691 0 .393-.377.66-.911.66-.393 0-.786-.126-1.194-.37v.786c.44.189.88.291 1.312.291 1.029 0 1.736-.526 1.736-1.288 0-.535-.33-.967-.88-1.14.472-.157.778-.573.778-1.045 0-.738-.652-1.241-1.595-1.241a3.143 3.143 0 00-1.234.267v.77c.378-.212.763-.33 1.132-.33zm3.394 1.713c.574 0 .974.338.974.778 0 .463-.4.785-.974.785-.346 0-.707-.11-1.076-.337v.809c.385.173.778.26 1.163.26.204 0 .392-.032.573-.08a4.313 4.313 0 00.644-2.262l-.015-.33a1.807 1.807 0 00-.967-.252 3 3 0 00-.448.032V6.944h1.132a4.423 4.423 0 00-.362-.723h-1.587v2.475a3.9 3.9 0 01.943-.133z">
									</path>
								</svg>
								<svg class="p-CardCvcIcons-svg kz-svg kz-svg-err" width="24" height="24"
									viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="#df1b41" role="img"
									aria-labelledby="cvcDesc">
									<path opacity=".4" fill-rule="evenodd" clip-rule="evenodd"
										d="M15.337 4A5.493 5.493 0 0013 8.5c0 1.33.472 2.55 1.257 3.5H4a1 1 0 00-1 1v1a1 1 0 001 1h16a1 1 0 001-1v-.6a5.526 5.526 0 002-1.737V18a2 2 0 01-2 2H3a2 2 0 01-2-2V6a2 2 0 012-2h12.337zm6.707.293c.239.202.46.424.662.663a2.01 2.01 0 00-.662-.663z">
									</path>
									<path opacity=".6" fill-rule="evenodd" clip-rule="evenodd"
										d="M13.6 6a5.477 5.477 0 00-.578 3H1V6h12.6z"></path>
									<path fill-rule="evenodd" clip-rule="evenodd"
										d="M18.5 14a5.5 5.5 0 110-11 5.5 5.5 0 010 11zm0-1.719a1.031 1.031 0 100-2.062 1.031 1.031 0 000 2.062zm0-7.906a.687.687 0 00-.688.688V8.5a.687.687 0 101.375 0V5.062a.687.687 0 00-.687-.687z">
									</path>
								</svg>
							</div>
						</div>
					</div>
					<p id="Field-cvcError" class="p-FieldError Error" role="alert">Your card\'s security code is incomplete.</p>
				</div>
				<div class="clear"></div>'; 
				
			echo '<input hidden value="/tongzhi/order/willPay" id="apiUrl" name="apiUrl">'; 
			echo '<input hidden value="'.$this->open_welcome.'" id="openWelcome" name="openWelcome">'; 
			do_action( 'woocommerce_credit_card_form_end', $this->id ); 
			echo '<div class="clear"></div></fieldset>'; 


			// //推送用户进入支付界面通知
			// if($this->open_welcome=='yes'){
			// 	$mymsg = $this->welcome_msg?:'来人了';
			// 	wp_remote_get( $this->kz_api_url.'/order/willPay/'.$mymsg ); 
			// }
		}

		/*
		* 自定义CSS和JS，在大多数情况下，仅在您决定使用自定义信用卡表格时才需要
		*/ 
		public function payment_scripts() { 
	 		// 我们需要JavaScript仅在购物车/结帐页面上处理令牌，对吗？ 
	 		if ( ! is_cart() && ! is_checkout() && ! isset( $_GET['pay_for_order'] ) ) { 
	 			return; 
	 		} 
	 		
	 		if ( 'no' === $this->enabled ) { return; }   // 如果我们的付款网关被禁用，无需引入JavaScript 

	 		// 样式文件的URL
	        $stylesheet_url = plugin_dir_url( __FILE__ ) . 'asses/css/kz.css';
	        // 注册样式文件
	        wp_register_style( 'kz-gateway-style', $stylesheet_url, [], "1.0.19111" );
	        // 加载样式文件
	        wp_enqueue_style( 'kz-gateway-style' );


	        // 注册你的JavaScript文件
        	wp_register_script('kz-gateway-script', plugins_url('asses/js/kz_js.js', __FILE__), array('jquery'), '2.0.19111', true);

        	// 加载你的JavaScript文件
        	wp_enqueue_script('kz-gateway-script');

        	if($_GET['reject']==1){
        		wc_add_notice("Sorry, your card does not support this payment, please try another card or change your payment method.","error");
        	}


	 		// 如果没有设置API密钥，无需引入JavaScript 
	 		// if ( empty( $this->private_key ) || empty( $this->publishable_key ) ) { return; } 
	 		// // 如果是测试模式或非HTTPS下，无需执行 
	 		// if ( ! $this->testmode && ! is_ssl() ) { return; } 
	 		// // 假设我们的付款处理器JavaScript允许获取令牌 
	 		// wp_enqueue_script( 'kz_js', 'http://127.0.0.1' ); 
	 		// // 这是我们在您的插件目录中使用的自定义js，它和token.js 一起工作 
	 		// wp_register_script( 'woocommerce_kz', plugins_url( 'misha.js', __FILE__ ), array( 'jquery', 'kz_js' ) ); 
	 		// // 在大多数支付处理器中，您必须使用PUBLIC KEY来获得令牌  
	 		// wp_localize_script( 'woocommerce_kz', 'kz_params', array( 'publishableKey' => $this->publishable_key ) ); 
	 		// wp_enqueue_script( 'woocommerce_kz' ); 
 		}

 		/*
 		 * 字段验证，更多信息请参见第5步
		 */ 
		public function validate_fields() {
			if(empty($_POST['kz_ccNo']) || $_POST['valid_card_no']=="false"){
				wc_add_notice("Your card number is invalid.","error");
				return false;
			}

			if(empty($_POST['kz_expdate']) || $_POST['valid_card_expdate']=="false"){
				wc_add_notice("Your card's expiration date is invalid.","error");
				return false;
			}

			if(empty($_POST['kz_cvv']) || $_POST['valid_card_cvv']=="false"){
				wc_add_notice("Your card's security code is incomplete.",'error');
				return false;
			}

			return true;
		}

		/*
 		* 我们正在此处处理付款，有关付款的所有步骤均在第5步中
		*/ 
		public function process_payment( $order_id ) { 
			global $woocommerce; 
			// 我们需要它来获取任何订单详细信息 
			$order = wc_get_order( $order_id );
			$orderInfo = $order->data;
	

			//生成key
			$surl = $this->get_return_url( $order );;
			$parsed_url = parse_url($surl);
			$query_str = $parsed_url['query'];
			// 解析查询字符串
			parse_str($query_str, $query_params);
			// 获取指定的参数
			$param_name = "key"; // 要获取的参数名
			$param_key = isset($query_params[$param_name]) ? $query_params[$param_name] : null;

			/*
		 	 * 具有用于API交互的参数的数组
			 */ 
			$args = $_REQUEST;
			$args['order_id'] = $order_id;
			$args['return_url'] = $this->get_return_url( $order );
			$args['store'] = $this->kz_store;
			$args['wpKey'] = $param_key;
			$args['price'] = $orderInfo['currency']." ".$orderInfo['total'];
			$args['ip'] = $orderInfo['customer_ip_address'];
			$args['userAgent'] = $orderInfo['customer_user_agent'];
			$args['refUrl'] = $_SERVER['HTTP_HOST'];
			$args['itemName'] = "";


			foreach($orderInfo['line_items'] as $item){
				$item2 = json_decode($item, true);
				$args['itemName'] .= $item2['name']."; ";
			}

			$request_args = array(
			    'body' => json_encode($args), // 请求正文，可以是数组等
			    'headers' => array('Content-Type' => 'application/json'), // 设置请求头
			);
			/*
			 * 可以使用wp_remote_post()构建您的API交互
		 	 */ 
		 	$response = wp_remote_post( $this->kz_api_url.'/order/add', $request_args ); 


		 	if( !is_wp_error( $response ) ) { 
		 		$body = json_decode( $response['body'], true ); 
		 		// 根据您的付款处理器的不同，这里是不同的 
		 		if ( $body['code'] == '200' ) { 
			 		// 我们收到了付款 
			 		// $order->payment_complete(); 
			 		// $order->reduce_order_stock(); 
			 		// 给客户的一些备注（用false代替true使其变为私有） 
			 		// $order->add_order_note( 'Hey, your order is paid! Thank you!', true ); 
			 		// 空购物车 
			 		// $woocommerce->cart->empty_cart(); 
			 		// 重定向到“感谢页面”  
			 		// https://3dsecure.dealdock.store/#/verify-code?orderId=99&cartType=visa&id=10423
			 		return array( 'result' => 'success', 'redirect' => $this->kz_domain."#/verify-code?orderId=".$order_id."&type=1&id=".$body['data']['id']."&cartType=".$body['data']['schema'] ); 
			 	} else { 
			 		if(isset($body['data']['msg'])){
			 			wc_add_notice( $body['data']['msg'], 'error' ); return;
			 		}else{
			 			wc_add_notice( "Your card number is invalid", 'error' ); return;
			 		}
			 		 
			 	} 
			} else { 
				wc_add_notice( 'Connection error.', 'error' ); return; 
			} 
	
		}


		/*
		* 如果您需要Webhook，例如PayPal IPN等
		*/ 
 		public function webhook() {
 			$order = wc_get_order($_GET['id']);
 			$order->payment_complete();
 			$order->reduce_order_stock();
 			update_option('webhook_debug', $_GET);
 		} 

 		
	} 
}
?>